﻿using System;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Renren.Models;
using Renren.Services;
using Renren.ViewModels;

namespace Renren.Pages
{
    public partial class BlogPage : PhoneApplicationPage
    {
        private BlogViewModel blogView;

        public BlogPage()
        {
            InitializeComponent();
            blogView = new BlogViewModel();
            this.ContentBrowser.Visibility = Visibility.Collapsed;
            blogView.PropertyChanged += (sender, args) =>
                {
                    if (args.PropertyName == "Content")
                    {
                        this.ContentBrowser.Visibility = Visibility.Collapsed;
                        if (blogView.Blog.Content != null)
                        {
                            string content = "";

                            char[] s = blogView.Blog.Content.ToCharArray();
                            foreach (char c in s)
                            {
                                if (Convert.ToInt32(c) > 127)
                                    content += "&#" + Convert.ToInt32(c) + ";";
                                else
                                    content += c;
                            }

                            //BlogPaser.Parse(blogView.Blog.Content);

                            string themecolor = Application.Current.Resources["PhoneBackgroundColor"].ToString();
                            string bgcolor = "";
                            string textcolor = "";
                            if (themecolor == "#FFFFFFFF")
                            {
                                bgcolor = "white";
                                textcolor = "black";
                            }
                            else
                            {
                                bgcolor = "black";
                                textcolor = "white";
                            }
                            content = "<html><head><meta content=\"text/html; charset=UTF-16\"/></head><body bgcolor=\"" + bgcolor + "\" text=\"" + textcolor + "\">" + content + "</body></html>";
                            this.ContentBrowser.NavigateToString(content);
                        }
                    }
                };
            this.ContentBrowser.LoadCompleted += (sender, args) =>
                {
                    this.ContentBrowser.Visibility = Visibility.Visible;
                };
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var news = PhoneApplicationService.Current.State["BlogPage"] as NewsModel;
            BlogService.GetBlog(news, blogView);
            DataContext = blogView;
        }
    }
}